#include "OriginImageModel.hpp"
#include <cstring>
#include <filesystem>
#include <fmt/format.h>
#include <pthread.h>
#include <stdexcept>
#include <yaml-cpp/yaml.h>

using namespace std::chrono_literals;

OriginImageModel::OriginImageModel(
    const std::vector<std::string> &cameraIDList, long ImageSize,
    std::function<void(const std::vector<ImageType> &)> func)
    : newImageCallback(func), controlMsgQueue("/HBTY_MSGSERVER_CAMERACOLLEGE") {
  // if(!std::filesystem::exists(configPath))
  //   throw std::runtime_error("无法打开原始图像配置文件");
  // YAML::Node config=YAML::LoadFile(configPath);
  // for(YAML::const_iterator
  // it=config["shm"].begin();it!=config["shm"].end();it++)
  //   sharedMemoryList.emplace_back(it->as<std::string>(),config["shm_size"].as<int>());
  // //memory_lock.reset(new POSIX_Semaphore("/HBTY_ORIMAGE_SEMAPHORE"));
  for (const auto &i : cameraIDList)
    sharedMemoryList.emplace_back(i, ImageSize);
}

OriginImageModel::~OriginImageModel() {
  if (workThread.joinable()) {
    pthread_cancel(threadID);
    workThread.join();
  }
}

void OriginImageModel::Boot() {
  workThread = std::thread([this]() {
    threadID = pthread_self();
    std::vector<ImageType> imageList(sharedMemoryList.size());
    bool continueFlag = false;
    while (true) {
      std::this_thread::sleep_for(50ms);
      // memory_lock->Lock();
      for (int i = 0; i < imageList.size(); i++) {
        memcpy(&(imageList[i]), sharedMemoryList[i].GetMemory(),
               sizeof(ImageType));
        if (imageList[i].uuid[0] == '\0') {
          continueFlag = true;
          break;
        } else
          continueFlag = false;
        imageList[i].data = new unsigned char[imageList[i].data_size];
        memcpy(imageList[i].data,
               sharedMemoryList[i].GetMemory() + sizeof(ImageType),
               imageList[i].data_size);
      }
      // memory_lock->Unlock();
      if (continueFlag)
        continue;
      newImageCallback(imageList);
    }
  });
}

void OriginImageModel::GetMemoryCallback(std::string val) {
  std::vector<ImageType> imageList(sharedMemoryList.size());
  // memory_lock->Lock();
  for (int i = 0; i < imageList.size(); i++) {
    memcpy(&(imageList[i]), sharedMemoryList[i].GetMemory(), sizeof(ImageType));
    imageList[i].data = new unsigned char[imageList[i].data_size];
    memcpy(imageList[i].data,
           sharedMemoryList[i].GetMemory() + sizeof(ImageType),
           imageList[i].data_size);
  }
  // memory_lock->Unlock();
  newImageCallback(imageList);
}
